<!--
 * @Description:
 * @Author: cgt
 * @Date: 2021-11-26 09:37:25
 * @LastEditors: cgt
 * @LastEditTime: 2021-12-28 20:01:25
-->
<template>
  <div>
    <el-button type="primary" @click="init">初始化</el-button>
  </div>
</template>

<script>
import mixins from '../mixins';

var lineFeature = turf.lineString([[104.08036434740376, 30.649861818254678], [104.08273181753566, 30.64867070971674], [104.08545890338155, 30.64860883354804], [104.08599233336128, 30.64931525078991], [104.0837747031128, 30.64975869255457], [104.08266588798853, 30.649980412673756]]);
lineFeature.properties.color = '#ff0000';
export default {
  name: 'SliceTool',
  props: {
    getMap: {
      type: Function,
      required: true
    },
    getTool: {
      type: Function,
      required: true
    },
    mapLoadSuccess: Boolean
  },
  data() {
    return {
      initialized: false
    };
  },
  mixins: [mixins],
  methods: {
    init() {
      if(this.initialized) {
        return;
      }
      this.initialized = true;
      this.getMap().impl.map.on('click', this.updateData);
      this.getMap().impl.map.addSource('_test_source', {
        type: 'geojson',
        data: {
          type: 'FeatureCollection',
          features: [

          ]
        }
      });
      this.getMap().impl.map.addLayer({
        id: '_test_symbol_layer',
        type: 'symbol',
        source: '_test_source',
        filter: ['==', '$type', 'Point'],
        layout: {
          'icon-image': '9060001',
          'icon-rotate': { 'type': 'identity', 'property': 'rotate' }
        }
      });
      this.getMap().impl.map.addLayer({
        id: '_test_fill_layer',
        type: 'fill',
        source: '_test_source',
        filter: ['==', '$type', 'Polygon'],
        paint: {
          'fill-color': '#ff0000',
          'fill-opacity': 0.3
        }
      });
      this.getMap().impl.map.addLayer({
        id: '_test_line_layer',
        type: 'line',
        source: '_test_source',
        filter: ['==', '$type', 'LineString'],
        paint: {
          'line-color': ['get', 'color']
        }
      });
      this.updateSource([lineFeature]);
      this.$notify({ message: '点击线绘制圆进行切割' });
    },
    updateData(e) {
      var point = e.lngLat.toArray();
      var circle = turf.circle(turf.point(point), 6 / 1000, {
        steps: 100
      });
      // eslint-disable-next-line no-use-before-define
      var sliceInfo = SliceUtil.slice(lineFeature, circle);

      var {
        start, finish, between, rotate
      } = sliceInfo;
      console.log('rotate', rotate);
      if(start && finish && between) {

        start.properties.color = '#082188';
        finish.properties.color = '#00ff00';
        between.properties.color = '#ef43bf';
        var pointFeature = turf.point(point);
        pointFeature.properties.rotate = rotate;
        this.updateSource([
          circle,
          pointFeature,
          start, finish, between
        ]);
      }else{
        this.$notify({ message: '无交点', type: 'info' });
      }
    },
    updateSource(features) {

      this.getMap().impl.map.getSource('_test_source').setData(turf.featureCollection(
        [...features]
      ));
    }


  }
};


var SliceUtil = {
  slice(line, polygon) {
    var intersects = turf.lineIntersect(line, polygon);
    console.log('intersects', intersects);
    if(intersects.features.length === 2) {
      var [intersectPoint1, intersectPoint2] = intersects.features;
      // 两个交点才符合规则
      // 取交叉点的最近点
      var nearInfo1 = turf.nearestPointOnLine(line, intersectPoint1),
        nearInfo2 = turf.nearestPointOnLine(line, intersectPoint2);
        // 从最近点信息里获取与哪个线段交叉
      var nearSegmentIndex1 = nearInfo1.properties.index,
        nearSegmentIndex2 = nearInfo2.properties.index;
      var segments = turf.lineSegment(line);
      var frontLineCoords = null, betweenLineCoords = null, afterLineCoords = null;
      if(nearSegmentIndex1 === nearSegmentIndex2) {
        // 在同一条线段上
        // 获取交叉的线段
        var intersectSegment = segments.features[nearSegmentIndex1];
        var intersectSegmentCoords = turf.getCoords(intersectSegment);
        // 判断两个交点与起点的距离
        var dis1 = turf.distance(intersectPoint1, turf.point(intersectSegmentCoords[0])),
          dis2 = turf.distance(intersectPoint2, turf.point(intersectSegmentCoords[0]));
        frontLineCoords = segments.features.slice(0, nearSegmentIndex1)
          .map((k) => turf.getCoords(k.geometry))
          .flat();
        afterLineCoords = segments.features.slice(nearSegmentIndex1 + 1)
          .map((k) => turf.getCoords(k.geometry))
          .flat();
        if(dis1 < dis2) {
          // 正序
          frontLineCoords = [...frontLineCoords, ...[intersectSegmentCoords[0], turf.getCoord(intersectPoint1)]];
          afterLineCoords = [...[turf.getCoord(intersectPoint2), intersectSegmentCoords[1]], ...afterLineCoords];
          betweenLineCoords = [turf.getCoord(intersectPoint1), turf.getCoord(intersectPoint2)];
        }else{
          // 反序
          frontLineCoords = [...frontLineCoords, ...[intersectSegmentCoords[0], turf.getCoord(intersectPoint2)]];
          afterLineCoords = [...[turf.getCoord(intersectPoint1), intersectSegmentCoords[1]], ...afterLineCoords];
          betweenLineCoords = [turf.getCoord(intersectPoint2), turf.getCoord(intersectPoint1)];

        }
      }else{
        // 获取交叉的线段
        var intersectSegment1 = segments.features[nearSegmentIndex1];
        var intersectSegmentCoords1 = turf.getCoords(intersectSegment1);
        var intersectSegment2 = segments.features[nearSegmentIndex2];
        var intersectSegmentCoords2 = turf.getCoords(intersectSegment2);
        if(nearSegmentIndex1 < nearSegmentIndex2) {
          frontLineCoords = segments.features.slice(0, nearSegmentIndex1)
            .map((k) => turf.getCoords(k.geometry))
            .flat();
          afterLineCoords = segments.features.slice(nearSegmentIndex2 + 1)
            .map((k) => turf.getCoords(k.geometry))
            .flat();

          frontLineCoords = [...frontLineCoords, ...[intersectSegmentCoords1[0], turf.getCoord(intersectPoint1)]];
          afterLineCoords = [...[turf.getCoord(intersectPoint2), intersectSegmentCoords2[1]], ...afterLineCoords];
          betweenLineCoords = [];
          betweenLineCoords.push(turf.getCoord(intersectPoint1));
          betweenLineCoords.push(intersectSegmentCoords1[1]);
          for(let i = nearSegmentIndex1 + 1;i < nearSegmentIndex2;i++) {
            let _segment = segments.features[i];
            let _coords = turf.getCoords(_segment);
            betweenLineCoords.push(..._coords);
          }
          betweenLineCoords.push(intersectSegmentCoords2[0]);
          betweenLineCoords.push(turf.getCoord(intersectPoint2));
        }else{
          frontLineCoords = segments.features.slice(0, nearSegmentIndex2)
            .map((k) => turf.getCoords(k.geometry))
            .flat();
          afterLineCoords = segments.features.slice(nearSegmentIndex1 + 1)
            .map((k) => turf.getCoords(k.geometry))
            .flat();

          frontLineCoords = [...frontLineCoords, ...[intersectSegmentCoords2[0], turf.getCoord(intersectPoint2)]];
          afterLineCoords = [...[turf.getCoord(intersectPoint1), intersectSegmentCoords1[1]], ...afterLineCoords];
          betweenLineCoords = [];
          betweenLineCoords.push(turf.getCoord(intersectPoint2));
          betweenLineCoords.push(intersectSegmentCoords2[1]);
          for(let i = nearSegmentIndex2 + 1;i < nearSegmentIndex1;i++) {
            let _segment = segments.features[i];
            let _coords = turf.getCoords(_segment);
            betweenLineCoords.push(..._coords);
          }
          betweenLineCoords.push(intersectSegmentCoords1[0]);
          betweenLineCoords.push(turf.getCoord(intersectPoint1));

        }
      }
      console.log('lineCoords', turf.getCoords(line));
      console.log('frontLineCoords', frontLineCoords);
      console.log('betweenLineCoords', betweenLineCoords);
      console.log('afterLineCoords', afterLineCoords);
      return {
        start: turf.lineString(frontLineCoords),
        finish: turf.lineString(afterLineCoords),
        between: turf.lineString(betweenLineCoords),
        rotate: turf.bearing(betweenLineCoords[0], betweenLineCoords[betweenLineCoords.length - 1]),
        intersects: intersects
      };
    }

    return {
      start: null,
      finish: null,
      between: null,
      rotate: null,
      intersects: intersects
    };

  }
};
window.SliceUtil = SliceUtil;
</script>

<style></style>
